MATLAB计算小数数组的最小公倍数和最大公因数

目录

1. 基本思想

2. DEMO

 3. 计算最小公倍数(LCD)

 4. 计算最大公因数(GCM)


1. 基本思想

把数组乘以数次10,直到变成整数数组为止;遍历整数数组的元素,用matlab自带的lcm和gcd函数;求出整数数组的最小公倍数和最大公因数之后再除以相应次数的10

(其实很简单,就是不知道为啥网上没找到相应的函数,就自己速度弄了一个;写得很急,如果发现有中间有什么问题请联系我!)

2. DEMO

array = [0.1, 0.02, 3, 0.25];
lcm = LCM(array);
gcd = GCD(array);

disp(['LCM: ', num2str(lcm)])
disp(['GCD: ', num2str(gcd)]);

运行结果: 

 3. 计算最小公倍数(LCD)

function result = LCM(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
    tmp = tmp * 10;
    exp = exp + 1;
end
result = lcm_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
    result = double(result) / 10^exp;
end
end

 % Calculate the LCM of an integer array
function result = lcm_array(array, n)
result = array(1);
for i = 1:n-1
    result = lcm(result,array(i+1)); 
end
end

这里面用到一个判定被乘了10的数组是否已经变成整数了:

function result = is_intarray(array)
tmp = round(array);
if (abs(array - tmp) < 10^(-10))
    result = 1;
else
    result = 0;
end
end

 4. 计算最大公因数(GCM)

function result = GCD(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
    tmp = tmp * 10;
    exp = exp + 1;
end
result = gcd_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
    result = double(result) / 10^exp;
end
end

% Calculate the GCD of an integer array
function result = gcd_array(array, n)
result = array(1);
for i = 1:n-1
    result = gcd(result,array(i+1)); 
end
end

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值